package com.personal.system.service.impl.content.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.personal.common.result.PageUtils;
import com.personal.common.result.Result;
import com.personal.system.config.SecurityUtil;
import com.personal.system.constant.MessageConstant;
import com.personal.system.entity.content.Article;
import com.personal.system.entity.content.Collect;
import com.personal.system.entity.content.Tags;
import com.personal.system.entity.vo.ApiArticleListVO;
import com.personal.system.listener.SystemNoticeHandle;
import com.personal.system.mapper.content.ArticleMapper;
import com.personal.system.mapper.content.CollectMapper;
import com.personal.system.mapper.content.TagsMapper;
import com.personal.system.service.content.web.ApiCollectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ApiCollectServiceImpl implements ApiCollectService {

    private final CollectMapper collectMapper;

    private final ArticleMapper articleMapper;

    private final SecurityUtil securityUtil;

    private final TagsMapper tagsMapper;

    /**
     * 我的收藏列表
     * @return
     */
    @Override
    public Result selectCollectList() {
        String userId = securityUtil.checkLogin();
        Page<ApiArticleListVO> list = collectMapper.selectCollectList(
                new Page<>(PageUtils.getPageNo(),PageUtils.getPageSize()),userId);
        list.getRecords().forEach(item ->{
            List<Tags> tags = tagsMapper.selectTagByArticleId(item.getId());
            item.setTagList(tags);
        });
        return Result.ok(list);
    }

    /**
     * 收藏文章
     * @param articleId 文章id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result collect(Integer articleId) {
        String userId = securityUtil.checkLogin();
        Collect collect = Collect.builder().userId(userId).articleId(articleId).build();
        collectMapper.insert(collect);
        // 发送系统通知
        Article article = articleMapper.selectById(articleId);
        SystemNoticeHandle.sendNotice(article.getUserId(), MessageConstant.MESSAGE_COLLECT_NOTICE,MessageConstant.SYSTEM_MESSAGE_CODE,articleId,null,null);
        return Result.ok();
    }

    /**
     * 取消收藏
     * @param articleId 文章id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result cancel(Integer articleId) {
        String userId = securityUtil.checkLogin();
        collectMapper.delete(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUserId,userId).eq(Collect::getArticleId,articleId));
        return Result.ok();
    }
}
